package bTree.LeetCode;

public class 解数独 {

    public void solveSudoku(char[][] board) {
        backTracking(board);
    }

    private boolean backTracking(char[][] board) {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.') {
                    continue;
                }
                for (char c = '1'; c <= '9'; c++) {
                    if (isValid(board, i, j, c)) {
                        board[i][j] = c;
                        if (backTracking(board)) {
                            return true;
                        }
                        board[i][j]='.';
                    }

                }
                return false;
            }
        }
        return true;
    }

    private boolean isValid(char[][] board, int row, int line, char c) {
        for (int i = 0; i < 9; i++) {
            if (board[row][i] == c) {
                return false;
            }
        }
        for (int i = 0; i <= 9; i++) {
            if (board[i][line] == c) {
                return false;
            }
        }
        int row2 = row / 3;
        int line2 = line / 3;
        for (int i = row2 * 3; i < row2 * 3 + 3; i++) {
            for (int j = line2 * 3; j < line2 * 3+3; j++) {
                if (board[i][j] == c) {
                    return false;
                }
            }
        }
        return true;
    }
}